package com.fenghao.subject.domain.handler.subject;

import com.fenghao.subject.common.enums.SubjectInfoTypeEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 题目类型工厂类
 */
@Component
public class SubjectTypeHandleFactory implements InitializingBean {
    @Resource
    private List<SubjectTypeHandler> subjectTypeHandlerList;

    private Map<SubjectInfoTypeEnum, SubjectTypeHandler> subjectTypeHandlerMap = new HashMap<>();

    // 重写 InitializingBean 接口下的 afterPropertiesSet 对 subjectTypeHandlerList进行初始化
    @Override
    public void afterPropertiesSet() {
        subjectTypeHandlerMap = subjectTypeHandlerList.stream()
                .collect(Collectors.toMap(
                        SubjectTypeHandler::getHandlerType,
                        subjectTypeHandler -> subjectTypeHandler));
    }


    // 获取对应的策略
    public SubjectTypeHandler getSubjectTypeHandler(int subjectType) {
        // 通过枚举值拿到枚举类型
        SubjectInfoTypeEnum subjectInfoTypeEnum = SubjectInfoTypeEnum.getEnumByCode(subjectType);
        // 通过枚举得到策略并返回
        SubjectTypeHandler subjectTypeHandler = subjectTypeHandlerMap.get(subjectInfoTypeEnum);
        return subjectTypeHandler;
    }


}
